﻿namespace MicroCloud.Utils
{
    /// <summary>
    /// 比较器辅助类，用于快速创建<see cref="IComparer{T}"/>接口的实例
    /// </summary>
    /// <example>
    /// var comparer1 = Comparison[Person].CreateComparer(p => p.ID); var comparer2 = Comparison[Person].CreateComparer(p => p.Name); var comparer3 = Comparison[Person].CreateComparer(p => p.Birthday.Year)
    /// </example>
    /// <typeparam name="T">要比较的类型</typeparam>
    public static class ComparisonHelper<T>
    {
        /// <summary>
        /// 创建指定对比委托<paramref name="keySelector"/>的实例
        /// </summary>
        /// <typeparam name="TV"></typeparam>
        /// <param name="keySelector"></param>
        /// <returns></returns>
        public static IComparer<T> CreateComparer<TV>(Func<T, TV> keySelector)
        {
            return new CommonComparer<TV>(keySelector);
        }

        /// <summary>
        /// 创建指定对比委托<paramref name="keySelector"/>与结果二次比较器<paramref name="comparer"/>的实例
        /// </summary>
        /// <typeparam name="TV"></typeparam>
        /// <param name="keySelector"></param>
        /// <param name="comparer"></param>
        /// <returns></returns>
        public static IComparer<T> CreateComparer<TV>(Func<T, TV> keySelector, IComparer<TV> comparer)
        {
            return new CommonComparer<TV>(keySelector, comparer);
        }

        /// <summary>
        /// 普通比较器
        /// </summary>
        /// <typeparam name="TV"></typeparam>
        private class CommonComparer<TV> : IComparer<T>
        {
            //字段
            private readonly IComparer<TV> _comparer;
            private readonly Func<T, TV> _keySelector;

            /// <summary>
            /// 初始化一个普通比较器 <see cref="CommonComparer{TV}"/> 的新实例
            /// </summary>
            /// <param name="keySelector"></param>
            /// <param name="comparer"></param>
            public CommonComparer(Func<T, TV> keySelector, IComparer<TV> comparer)
            {
                _keySelector = keySelector;
                _comparer = comparer;
            }

            /// <summary>
            /// 初始化一个普通比较器 <see cref="CommonComparer{TV}"/> 的新实例
            /// </summary>
            /// <param name="keySelector"></param>
            public CommonComparer(Func<T, TV> keySelector)
                : this(keySelector, Comparer<TV>.Default)
            { }

            #region 方法
            /// <summary>
            /// 比较两个对象并返回一个值，该值指示一个对象是否小于、等于或大于另一个对象
            /// </summary>
            /// <param name="x">第一个要比较的对象</param>
            /// <param name="y">要比较的第二个对象</param>
            /// <returns>表示x和y的相对值的有符号整数，如下表所示。值表示小于零x小于y。零x等于y。大于零x大于y</returns>
            public int Compare(T x, T y)
            {
                return _comparer.Compare(_keySelector(x), _keySelector(y));
            }

            #endregion

        }

    }

}
